package business

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/business"
	businessReq "github.com/flipped-aurora/gin-vue-admin/server/model/business/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type ScoreService struct {
}

// CreateScore 创建分数记录
// Author [piexlmax](https://github.com/piexlmax)
func (scoreService *ScoreService) CreateScore(score *business.Score) (err error) {
	err = global.GVA_DB.Create(score).Error
	return err
}

// DeleteScore 删除分数记录
// Author [piexlmax](https://github.com/piexlmax)
func (scoreService *ScoreService) DeleteScore(score business.Score) (err error) {
	err = global.GVA_DB.Delete(&score).Error
	return err
}

// DeleteScoreByIds 批量删除分数记录
// Author [piexlmax](https://github.com/piexlmax)
func (scoreService *ScoreService) DeleteScoreByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]business.Score{}, "id in ?", ids.Ids).Error
	return err
}

// UpdateScore 更新分数记录
// Author [piexlmax](https://github.com/piexlmax)
func (scoreService *ScoreService) UpdateScore(score business.Score) (err error) {
	err = global.GVA_DB.Save(&score).Error
	return err
}

// GetScore 根据id获取分数记录
// Author [piexlmax](https://github.com/piexlmax)
func (scoreService *ScoreService) GetScore(id uint) (score business.Score, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&score).Error
	return
}

// GetScoreInfoList 分页获取分数记录
// Author [piexlmax](https://github.com/piexlmax)
func (scoreService *ScoreService) GetScoreInfoList(info businessReq.ScoreSearch) (list []business.Score, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&business.Score{})
	var scores []business.Score
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	if info.UserId != 0 {
		db = db.Where("user_id = ?", info.UserId)
	}
	if info.QuestionnaireUuid != "" {
		db = db.Where("questionnaire_uuid = ?", info.QuestionnaireUuid)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	var OrderStr string
	orderMap := make(map[string]bool)
	orderMap["mark"] = true
	if orderMap[info.Sort] {
		OrderStr = info.Sort
		if info.Order == "descending" {
			OrderStr = OrderStr + " desc"
		}
		db = db.Order(OrderStr)
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&scores).Error
	return scores, total, err
}
